package com.yuan.fmmall.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yuan.fmmall.vo.ResStatus;
import com.yuan.fmmall.vo.ResultVO;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @author Yuan
 */
//检查token是否合法或过期
@Component   //标注一个类为Spring容器的Bean
public class CheckTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //受限资源拦截器，访问的前提是已经登录，故在此处检查token
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if("OPTIONS".equalsIgnoreCase(method)){
            return true;
        }
        String token = request.getHeader("token");
        if(token == null){
            ResultVO resultVO = new ResultVO(ResStatus.LOGIN_FAIL_NOT, "请先登录！", null);
            doResponse(response,resultVO);
        }else{
            //若有token，则将此token与redis中的token进行对比查找
            String s = stringRedisTemplate.boundValueOps(token).get();
            if(s==null){
                //此token未查找到，两种可能，1、没登录过 2、登录过期了
                ResultVO resultVO = new ResultVO(ResStatus.LOGIN_FAIL_NOT, "请先登录！", null);
                doResponse(response,resultVO);
            }else {
                //在redis中找到了，那么重新调整一下此token的过期时间
                stringRedisTemplate.boundValueOps(token).expire(30, TimeUnit.MINUTES);
                return true;
            }
        }
        return false;
    }

    private void doResponse(HttpServletResponse response,ResultVO resultVO) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String s = new ObjectMapper().writeValueAsString(resultVO);//将Java对象转为Json格式的数据，用于后端Servlet向AJAX传递Json数据
        out.print(s);
        out.flush();
        out.close();
    }
}
